############################################
#               证书生成与维护
# 参数: $1 域名
###########################################

# 参数校验 - 域名需存在
if [ -z "${1}" ]; then
    echo "gen-cert <域名>"
    exit 1
fi

# 确保申请文件存放目录存在
if [ ! -e "challenges/${1}" ]; then
    echo "创建目录: challenges/${1}"
    mkdir -p "challenges/${1}"
fi

# 确保证书存放目录存在
if [ ! -e "cert" ]; then
    echo "创建目录: cert"
    mkdir "cert"
fi

# 确保account.key存在
if [ ! -e "account.key" ]; then
    echo "生成account.key"
    openssl genrsa 4096 > "account.key"
fi

# 确保证书密钥存在
if [ ! -e "cert/${1}.key" ]; then
    echo "生成证书密钥"
    openssl genrsa 4096 > "cert/${1}.key"
fi

# 确保证书签名申请存在
if [ ! -e "cert/${1}.csr" ]; then
    echo "生成csr"
    openssl req -new -sha256 -key "cert/${1}.key" -subj "/CN=${1}" > "cert/${1}.csr"
fi

# 确保脚本存在
if [ ! -e "acme_tiny.py" ]; then
    echo "下载脚本: acme_tiny.py"
    curl -LO "https://raw.githubusercontent.com/sidian123/acme-tiny/master/acme_tiny.py"
fi

# 获取已签名的证书
echo "获取证书"
python acme_tiny.py --account-key "./account.key" --csr "./cert/${1}.csr" --acme-dir "challenges/${1}" > "./cert/${1}.crt"
